﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections;
using System.Collections.ObjectModel;
using System.Diagnostics;
using ZGRemote.Common.Networking;
using ZGRemote.Server.Core.Handler;
using ZGRemote.Server.Core.Models;

namespace ZGRemote.Server.UI.ViewModels
{
    partial class RemoteViewModel : ViewModelBase
    {
        [ObservableProperty]
        private ObservableCollection<User> users;

        [ObservableProperty]
        private User? selectUser;

        [ObservableProperty]
        private bool isExpanded;

        public RemoteViewModel()
        {
            header = Core.Properties.Resources.Remote;
            users = new ObservableCollection<User>();
            App.Current.Server.Connect += Connect;
            App.Current.Server.DisConnect += DisConnect;
            App.Current.Server.ServerStop += ServerStop;
        }

        [RelayCommand]
        private void OpenRemoteShell()
        {
            if (SelectUser == null) return;
            OpenViewModel<RemoteShellViewModel>(SelectUser);
        }

        [RelayCommand]
        private void OpenRemoteFileExplorer()
        {
            if (SelectUser == null) return;
            OpenViewModel<RemoteFileExplorerViewModel>(SelectUser);
        }

        [RelayCommand]
        private void Disconnect()
        {
            if (SelectUser == null) return;
            RemoteHandler.Disconnect(SelectUser.UserContext);
        }

        private void OpenViewModel<T>(User user) where T : RemoteViewModelBase
        {
            var vm = App.Current.MainViewModel.RemoteViewModelList.
                Where(vm => vm.GetType() == typeof(T) && vm.User == user).FirstOrDefault();
            if (vm == null)
            {
                var constructor = typeof(T).GetConstructor(new Type[] { typeof(User) });
                vm = (T)constructor?.Invoke(new object[] { user })!;
                App.Current.MainViewModel.RemoteViewModelList.Add(vm);
            }
            App.Current.MainViewModel.NavigateTo(vm);
            IsExpanded = true;
        }

        private void Connect(User user)
        {
            App.Current.Dispatcher.BeginInvoke(() => { Users.Add(user); });
        }

        private void DisConnect(User user)
        {
            App.Current.Dispatcher.BeginInvoke(() => { Users.Remove(user); });
        }

        private void ServerStop()
        {
            App.Current.Dispatcher.BeginInvoke(() => { Users.Clear(); });
        }
    }
}
